package com.sflx.shortmessage.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sflx.shortmessage.entity.ShortUrl;
import com.sflx.shortmessage.service.ShortUrlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zengqingfa
 * @className ShortUrlController
 * @description
 * @create 2022/9/25 16:42
 */
@Controller
@Slf4j
public class ShortUrlRedirectController {

    @Resource
    private ShortUrlService shortUrlService;


    /**
     * 访问短链接重定向到长链接
     * 接口需要开通白名单
     *
     * @param shortUrlCode
     * @return
     */
    @GetMapping("/a/{shortUrlCode}")
    public void redirectLongURL(@PathVariable("shortUrlCode") String shortUrlCode, HttpServletResponse response) {
        ShortUrl shortUrl = shortUrlService.getOne(new LambdaQueryWrapper<ShortUrl>()
                .eq(ShortUrl::getShortUrlCode, shortUrlCode)
                .last("limit 1"));
        if (shortUrl == null) {
            throw new RuntimeException("链接不存在");
        }
        // 增加短链点击次数
        shortUrl.setClickCount(shortUrl.getClickCount() + 1);
        shortUrlService.updateById(shortUrl);
        try {
            //重定向到长链接
            response.sendRedirect(shortUrl.getLongUrl());
        } catch (IOException e) {
            log.error("重定向异常：{}", e.getMessage());
        }
    }

}